package com.bnd.controller;

import com.bnd.common.BaseResponse;
import com.bnd.common.ErrorCode;
import com.bnd.common.ResultUtils;
import com.bnd.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;

/**
 * 文件控制器
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @jakarta.annotation.Resource
    private FileService fileService;

    /**
     * 文件上传接口
     * @param file 上传的文件
     * @return 文件访问URL
     */
    @PostMapping("/upload")
    public BaseResponse<Object> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = fileService.uploadFile(file);
            return ResultUtils.success((Object)fileUrl);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 音频文件上传接口（带校验）
     * @param file 上传的音频文件
     * @return 文件访问URL
     */
    @PostMapping("/upload/audio")
    public BaseResponse<Object> uploadAudioFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = fileService.uploadAudioFile(file);
            return ResultUtils.success((Object)fileUrl);
        } catch (Exception e) {
            log.error("音频文件上传失败", e);
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "音频文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 文件下载接口
     * @param fileUrl 文件访问URL
     * @param response HTTP响应对象
     */
    @GetMapping("/download")
    public void downloadFile(@RequestParam String fileUrl, HttpServletResponse response) {
        try {
            fileService.downloadFile(fileUrl, response);
        } catch (Exception e) {
            log.error("文件下载失败，文件URL: {}", fileUrl, e);
            response.setStatus(404);
            try {
                response.getWriter().write("文件下载失败: " + e.getMessage());
            } catch (IOException ioException) {
                log.error("响应写入失败", ioException);
            }
        }
    }

    /**
     * 文件预览接口
     * @param fileUrl 文件访问URL
     * @return 文件资源
     */
    @GetMapping("/preview")
    public ResponseEntity<Resource> previewFile(@RequestParam String fileUrl) {
        try {
            Resource resource = fileService.previewFile(fileUrl);
            if (resource != null && resource.exists()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + fileUrl.substring(fileUrl.lastIndexOf("/") + 1) + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            log.error("文件预览失败，文件URL: {}", fileUrl, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 文件删除接口
     * @param fileUrl 文件访问URL
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public BaseResponse<String> deleteFile(@RequestParam String fileUrl) {
        boolean result = fileService.deleteFile(fileUrl);
        if (result) {
            return ResultUtils.success("文件删除成功");
        } else {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR, "文件删除失败，文件可能不存在");
        }
    }
}
